package com.sykj.bsc.zn.util;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class ViewExcel extends AbstractExcelView {
	private String[] titles;

	//����ָ���ı���ͷ
	public ViewExcel(String[] titles) {
		this.titles=titles;
	}
	@Override
	protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//��ȡ����
		List<Map<String, Object>> list = (List<Map<String, Object>>) model.get("excelList");
		//��workbook���һ��sheet
		HSSFSheet sheet = workbook.createSheet();
		sheet.setDefaultColumnWidth(15);
		HSSFCell cell=null;
		//��������
		for (int i = 0; i < titles.length; i++) {
			//��ȡλ��
			cell = getCell(sheet, 0, i);
			setText(cell, titles[i]);
		}
		//����д��
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map=list.get(i);
			HSSFRow row = sheet.createRow(i+1);
			for (int j = 0; j < titles.length; j++) {
				String title=titles[j];
				if(map.containsKey(title)){
					row.createCell(j).setCellValue(map.get(title)+"");
				}
			}
		}
		//��������ʱ�ͻ���Excel������ 
		String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls";  
		response.setContentType("application/vnd.ms-excel");     
		response.setHeader("Content-disposition", "attachment;filename=" + filename); 
		OutputStream ouputStream = response.getOutputStream();     
		workbook.write(ouputStream);     
		ouputStream.flush();     
		ouputStream.close();
	}
	
	
	
	

	
}
